<template>
  <!--关联商品-->
  <div>
    <!--关联商品-->
    <el-dialog
      title="关联商品"
      :visible="showModal"
      :modal-append-to-body="false"
      :append-to-body="true"
      width="60%"
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-row>
        <el-form ref="queryData" :model="queryData" label-width="100px">
          <el-row type="flex" :gutter="20">
            <!-- 当操作修改销售区域页面时，暂时注掉商品分类查询条件 -->
            <el-col :span="8"  v-if="!isSaleAreaPage">
              <template v-if="isAccurateSearchClassify">
                <el-form-item label="商品分类" prop="categoryName">
                  <el-input
                    v-model="queryData.categoryName"
                    prefix-icon="el-icon-search"
                    @focus="handleChooseGoodsClassify"
                    placeholder="请选择商品分类"
                  />
                </el-form-item>
              </template>
              <template v-else>
                <el-form-item label="商品分类" prop="categoryName">
                  <el-input
                    v-model="queryData.categoryName"
                    placeholder="请输入商品分类"
                  ></el-input>
                </el-form-item>
              </template>
            </el-col>
            <el-col :span="8">
              <el-form-item label="SPU编码" prop="spuNo">
                <el-input
                  v-model="queryData.spuNo"
                  placeholder="请输入SPU编码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品名称" prop="productName">
                <el-input
                  v-model="queryData.productName"
                  placeholder="请输入商品名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="isSaleAreaPage">
              <el-form-item label="供应商编码" prop="supplyUuid">
                <el-input
                  v-model="queryData.supplyUuid"
                  placeholder="请输入供应商编码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="end">
            <el-button
              type="primary"
              @click="handleQueryData"
              :disabled="tabpaneDisabled"
              >查询</el-button
            >
            <el-button
              @click="handleResetData('queryData')"
              :disabled="tabpaneDisabled"
              >清空</el-button
            >
            <el-button
              v-if="tabsStatus === 'notAssociated' ? true : false"
              type="primary"
              ghost
              @click="handleBatchAssociate"
              :disabled="tabpaneDisabled"
              >批量关联</el-button
            >
            <el-button
              v-else
              ghost
              @click="handleBatchCancel"
              :disabled="tabpaneDisabled"
              >批量取消</el-button
            >
          </el-row>
        </el-form>
      </el-row>
      <el-tabs
        v-model="tabsStatus"
        @tab-click="handleClickTabs"
        style="margin: 10px"
      >
        <el-tab-pane
          label="未关联"
          name="notAssociated"
          :disabled="tabpaneDisabled"
        >
        </el-tab-pane>
        <el-tab-pane
          label="已关联"
          name="isAssociated"
          :disabled="tabpaneDisabled"
        >
        </el-tab-pane>
      </el-tabs>
      <pl-table
        ref="multipleTable"
        size="mini"
        :row-height="45"
        border="border"
        use-virtual
        height="480"
        v-loading="tableLoading"
        :data="dataSource"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleCheckTableItem"
      >
        <!-- <pl-table-column fixed type="selection" width="50" /> -->
        <pl-table-column
          v-for="column in columns"
          :key="column.key"
          :prop="column.key"
          :label="column.title"
          :property="column.key"
          :align="column.align"
          :min-width="100"
          :fixed="column.fixed"
          :show-overflow-tooltip="true"
          :type="column.type"
        >
          <template v-if="column.slot === 'action'" v-slot="scope">
            <el-button
              v-if="tabsStatus === 'notAssociated'"
              type="success"
              size="mini"
              @click="handleAssociateGoods(scope.row, scope.$index)"
              >关联</el-button
            >
            <el-button
              v-else
              size="mini"
              @click="handleCancelGoods(scope.row, scope.$index)"
              >取消</el-button
            >
          </template>
        </pl-table-column>
      </pl-table>
      <div class="pagination_wrap">
        <el-pagination
          background
          :total="totalPage"
          :current-page="nowPage"
          :page-size="pageShow"
          :page-sizes="pageSizeOpts"
          @current-change="handleChangePage"
          @size-change="handleChangePageSize"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
      <el-row slot="footer" style="text-align: center">
        <el-button type="primary" @click="handleCloseModal">返回表单</el-button>
      </el-row>
    </el-dialog>
    <classification-goods-dialog
      ref="classifyRef"
      :visible.sync="searchClassifyModal"
      @getCategoryData="handleGetCategoryData"
    ></classification-goods-dialog>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { getValueFn } from './utils';
import spuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/spuDimension';
import classificationGoodsDialog from '@/components/common/dialog/associatedGoods/classificationGoodsDialog';
export default {
  mixins: [spuDimensionMixins],
  components: { classificationGoodsDialog },
  props: {
    /* 表格表头 */
    columns: {
      type: Array,
      required: true
    },
    /* 请求查询数据接口入参 */
    requestParams: {
      type: Array,
      required: true
    },
    /* 请求查询数据接口区别未关联和已关联的入参 */
    distinctParams: {
      type: Object
    },
    /* 查询接口及类型 */
    requestApi: {
      type: Object,
      required: true
    },
    /* 请求接口时，是否需要saleType入参，通过父组件传值决定 */
    saleType: {
      tyoe: String
    },
    /* 关联时存储的标识，如果不传默认是uuid */
    idType: {
      type: String
    },
    /* 是否需要精准查询商品分类 */
    isAccurateSearchClassify: {
      type: Boolean
    },
    pageSizeOpts: {
      type: Array,
      default () {
        return [10, 100, 500, 1000];
      }
    },
    /* 是否是销售区域的页面 */
    isSaleAreaPage: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      queryData: {
        spuNo: '', // spu编码
        productName: '', // 商品名称
        categoryName: '', // 商品分类
        categoryUuid: '', // 商品分类id
        supplyUuid: '', // 供应商编码
      },
      dataSource: [], // 表格数据
      tabsStatus: 'notAssociated', // 当前tabs页签
      nowPage: 1, // 当前页
      pageShow: 10, // 每页条数
      totalPage: 0, // 总条数
      tableLoading: false,
      checkTableItemList: [],
      isQueryRel: false,
      searchClassifyModal: false,
      tabpaneDisabled: false
    };
  },
  beforeDestroy () {
    this.DESTORY_STATE();
  },
  methods: {
    /* 打开选择分类弹框的方法 */
    handleChooseGoodsClassify () {
      this.searchClassifyModal = true;
      this.$refs.classifyRef.getLevelOneCategoryListAction('1');
    },
    /* 获取分类弹框选择分类内容的方法 */
    handleGetCategoryData (data) {
      this.queryData.categoryName = data.categoryName;
      this.queryData.categoryUuid = data.categoryUuid;
      this.getDataListAction();
    },
    /* 切换关联和未关联 */
    handleClickTabs () {
      if (this.getListFromMapFn().length === 0) {
        this.totalPage = 0;
      }
      this.nowPage = 1;
      this.getDataListAction();
    },
    /* 获取关联商品接口入参 */
    getApiParamsFn (data) {
      let { param, skuList } = data
      let params = {}
      if (this.isSaleAreaPage) {
        /* 修改销售区域特殊处理关联商品表单入参 */
        let {
          category, // 商品分类入参名称
          productName, // 商品名称入参名称
          spuNo // spu编码入参名称
        } = this.requestParams[0]
        let {
          notAssociated, // 未关联入参名称
          isAssociated // 已关联入参名称
        } = this.distinctParams
        param[category] = this.queryData.categoryName
        param[productName] = this.queryData.productName
        param[spuNo] = this.queryData.spuNo
        param.supplyUuid = this.queryData.supplyUuid
        if (this.tabsStatus === 'notAssociated') {
          param[notAssociated] = skuList
        } else {
          param[isAssociated] = skuList
        }
        params = {
          ...param,
          nowPage: this.nowPage,
          pageShow: this.pageShow
        }
      } else {
        params = {
          sortName: '',
          sortType: '',
          searchParam: JSON.stringify(param),
          nowPage: this.nowPage,
          pageShow: this.pageShow
        }
      }
      return params
    },
    /* 获取数据方法 */
    getDataListAction () {
      let { url, type } = this.requestApi;
      let requsetUrl = this.isSaleAreaPage ? url[0] : '';
      let uuidName = this.idType ? this.idType : 'uuid';
      let skuList = this.getListFromMapFn().map((item) => {
        return item[uuidName];
      });
      if (this.isAccurateSearchClassify && !this.queryData.categoryUuid) {
        this.$message({
          message: '请选择商品分类',
          type: 'warning',
          customClass: 'basic_page_message_zindex'
        });
        return false;
      }
      let param = _.cloneDeep(this.requestParams);
      if (this.saleType) {
        param.push({ name: 'saleType', value: this.saleType });
      }
      if (!this.isSaleAreaPage) {
        param.forEach((value) => {
          value.value = getValueFn(value, this.queryData);
        });
        if (this.tabsStatus === 'notAssociated') {
          let distinctParamsNotAssociated = _.cloneDeep(
            this.distinctParams.notAssociated
          );
          let i = _.findIndex(distinctParamsNotAssociated, (value) => {
            return !value.value;
          });
          distinctParamsNotAssociated[i].value = skuList.join(',');
          param.push(...distinctParamsNotAssociated);
          requsetUrl = url[0];
          this.isQueryRel = false;
        } else {
          let distinctParamsAssociated = _.cloneDeep(
            this.distinctParams.associated
          );
          let i = _.findIndex(distinctParamsAssociated, (value) => {
            return !value.value;
          });
          distinctParamsAssociated[i].value = skuList.join(',');
          param.push(...distinctParamsAssociated);
          requsetUrl = url[1] ? url[1] : url[0];
          this.isQueryRel = true;
        }
      }
      let data = this.getApiParamsFn({ param, skuList })
      if (skuList.length === 0 && this.tabsStatus === 'isAssociated') {
        this.dataSource = [];
        return;
      }
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.tableLoading = true;
      this.tabpaneDisabled = true;
      ApiRequest(requsetUrl, type, data, false)
        .then((res) => {
          if (res.retStatus === '1' && res.retData.results) {
            this.dataSource = res.retData.results;
            this.totalPage = res.retData.totalNum;
          } else {
            this.dataSource = [];
            this.totalPage = res.retData.totalNum;
          }
          this.tableLoading = false;
          this.tabpaneDisabled = false;
        })
        .catch(() => {
          this.tableLoading = false;
          this.tabpaneDisabled = false;
        });
    },
    /* 查询方法 */
    handleQueryData () {
      this.getDataListAction();
    },
    /* 清空方法 */
    handleResetData (name) {
      this.$refs[name].resetFields();
    },
    /* 批量关联方法 */
    handleBatchAssociate () {
      if (this.checkTableItemList.length === 0) {
        return;
      }
      this.checkTableItemList.forEach((value) => {
        this.ASSOCIATED_GOODS({ row: value, type: this.idType });
      });
      this.$nextTick(() => {
        this.getDataListAction();
      });
    },
    /* 批量取消方法 */
    handleBatchCancel () {
      if (this.checkTableItemList.length === 0) {
        return;
      }
      this.checkTableItemList.forEach((value) => {
        this.CANCEL_GOODS({ row: value, type: this.idType });
      });
      this.$nextTick(() => {
        this.getDataListAction();
      });
    },
    /* 关联方法 */
    handleAssociateGoods (row, index) {
      this.ASSOCIATED_GOODS({ row, type: this.idType });
      this.getDataListAction();
    },
    /* 取消方法 */
    handleCancelGoods (row, index) {
      this.CANCEL_GOODS({ row, type: this.idType });
      this.getDataListAction();
    },
    /* 表格数据勾选或勾选取消方法 */
    handleCheckTableItem (list) {
      this.checkTableItemList = list;
    },
    handleChangePage (page) {
      this.nowPage = page;
      this.getDataListAction();
    },
    handleChangePageSize (size) {
      this.nowPage = 1;
      this.pageShow = size;
      this.getDataListAction();
    },
    handleCloseModal () {
      this.nowPage = 1;
      this.pageShow = 10;
      this.tabsStatus = 'notAssociated';
      this.dataSource = [];
      this.handleResetData('queryData');
      this.$emit('getRowList');
      this.CHANGE_MODAL_SWITCH(false);
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .el-dialog__body {
  padding: 10px 20px;
}
/deep/ .el-dialog__header {
  border-bottom: 1px solid #e8eaec;
}
/deep/ .el-dialog__footer {
  border-top: 1px solid #e8eaec;
}
/* 查询清空批量操作栏样式 */
.options_wrap {
  /deep/ .ivu-btn {
    margin-left: 15px;
  }
  /deep/ .ivu-btn-ghost {
    margin-right: 10px;
  }
}

/* 分页样式 */
.pagination_wrap {
  text-align: center;
  margin-top: 10px;
}
</style>
